﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Modified by Rob Gustafson of The MITRE Corporation, 2011 -->
<!-- Copyright (c) 2011 MASAS Contributors.  Published under the
Clear BSD license.  See license.txt for the full text of the license.
-->
<head>
	<script type='text/javascript'>

	    //first, checks if it isn't implemented yet
	    if (!String.prototype.format) {
	        String.prototype.format = function () {
	            var args = arguments;
	            return this.replace(/{(\d+)}/g, function (match, number) {
	                return typeof args[number] != 'undefined'
                      ? args[number]
                      : match
	                ;
	            });
	        };
	    }

	    var ICNET_SERVER_URL = 'http://icnet-test.mitre.org'; // The location this form is hosted, used to get the possible event list
        var EVENT_LIST_URL =  'events/get_events.txt';
        var IPAWS_FORWARDER_SERVER_URL = 'http://127.0.0.1'; // The server that the results are posted to
        var IPAWS_FORWARDER_SERVER_PORT = 18000;
	    var timezone = getTimezoneString();
	    var timezone_ms = getTimezoneMs();
	    var labelForCAP1_1 = 'CAP 1.1';
	    var labelForCAP1_2 = 'CAP 1.2';
	    //var labelForCAP1_2_CMAS = 'CMAS (CAP 1.2)'; // has CMAM text
	    //var labelForCAP1_2_EAS = 'EAS (CAP 1.2)'; // has CMAM text and EAS Org, description field is required
	    //var generateInfoNode = true; // true for message types of ALERT and UPDATE
	    var locationLayer;
	    var navControl;
	    var editPanel;
	    var point_location = '';
	    var selection_circle_radius = '';
	    var polygon_string = '';
	    var locationCAPCard;
	    var geocodeArrays = new Array();
	    var referenceArray = new Array();
	    var defaultCards;
	    var cancelMessageCards;
	    var exampleReference = 'SENDER,IPAWS-CAP-Generator-XXXXXXXXXXXXX,YYYY-MM-DDTHH:MM:SS-HH:MM';
	    var generatedXML = 'none';
	    var capformVersionNumber = '1.12';
	    var capformSessionID = '';
	    // search for 'FIXME' - currently no major ones
	                     
	    function getTimezoneString() {
	        var d = new Date();
	        var tz_min = d.getTimezoneOffset();

	        var direction = "-";
	        if (tz_min < 0) {
	            direction = "+";
	        }
	        var hours = Math.abs(Math.floor(tz_min / 60));
	        var mins = tz_min % 60;

	        hours = zeroFill(hours, 2);
	        mins = zeroFill(mins, 2);
	        var str = "{0}{1}:{2}".format(direction, hours, mins);
	        return str;
	    }

	    function getTimezoneMs() {
	        var d = new Date();
	        var tz_min = d.getTimezoneOffset();
	        return -1 * tz_min * 60 * 1000;
	    }

	    function zeroFill( number, width )
	    {
	        width -= number.toString().length;
	        if ( width > 0 )
	        {
	            return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
	        }
	        return number + ""; // always return a string
	    }
	</script>
  <title>IPAWS CAP Generation Tool</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
	
  <link rel="stylesheet" type="text/css" href="post/ext-3.3.0/resources/css/ext-all.css"></link>
  <script src="post/ext-3.3.0/adapter/ext/ext-base.js" type="text/javascript"></script>
  <script type='text/javascript'>
      // IE 9 address search panel hack
      if (Ext.isIE6 && /msie 9/.test(navigator.userAgent.toLowerCase())) {
          Ext.isIE6 = Ext.isIE = false;
          Ext.isChrome = Ext.isIE9 = true;
      }</script>
  <script src="post/ext-3.3.0/ext-all.js" type="text/javascript"></script>

  <link rel="stylesheet" type="text/css" href="post/virtualkeyboard/virtualkeyboard.css"></link>
  <script type="text/javascript" src="post/virtualkeyboard/Ext.ux.VirtualKeyboard.js"></script>
  <script type="text/javascript" src="post/virtualkeyboard/Ext.ux.plugins.VirtualKeyboard.js"></script>

  <!-- OpenLayers needs to load before GeoExt -->
  <script src="post/OpenLayers-2.10/OpenLayers.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="post/GeoExt-1.0/resources/css/geoext-all-debug.css"></link>
  <script src="post/GeoExt-1.0/lib/GeoExt.js" type="text/javascript"></script>

  <script type="text/javascript" src="https://maps-api-ssl.google.com/maps/api/js?sensor=false&v=3.2"></script>

  <script type="text/javascript" src="post/js/json2.js"></script>
  <script type="text/javascript" src="post/js/JsonXml.js"></script>
  <script type="text/javascript" src="post/js/templates.js"></script>
  

  <style type="text/css">
    html, body {
      font:normal 12px verdana;
      margin:0;
      padding:0;
      border:0 none;
      overflow:hidden;
      height:100%;
    }
    #headerTitleBlock {
      float: left;
      font-size: 150%;
      font-weight: bold;
      padding: 3px;
    }
    #headerDetailBlock {
      float: right;
      padding: 5px;
      font-size: 85%;
    }
    .editPanel { top: 10px; left: 14px; position: absolute; }
    .editPanel div {
      margin-top: 10px;
      width: 24px;
      height: 24px;
      border: 1px solid white;
      background-color: white;
    }
    .olControlNavigationItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/pan_on.png");
    }
    .olControlNavigationItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/pan_off.png");
    }
    .pointButtonItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_point_on.png");
    }
    .pointButtonItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_point_off.png");
    }
	.polygonButtonItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_polygon_on.png");
    }
    .polygonButtonItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_polygon_off.png");
    }
	.circleButtonItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_circle_on.png");
    }
    .circleButtonItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/draw_circle_off.png");
    }
	.eraserButtonItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/remove_point_on.png");
    }
    .eraserButtonItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/remove_point_off.png");
    }
    .saveButtonItemActive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/save_features_on.png");
    }
    .saveButtonItemInactive {
      background-image: url("post/OpenLayers-2.10/theme/default/img/save_features_off.png");
    }
    .postingCard { margin: 25px; }
    .postingCard h1 { margin-bottom: 25px; font-weight: bold; font-size: 150%; }
    .postingCard a {
        display: block;
        padding: 10px;
        margin-bottom: 25px;
        border: 1px solid black;
        width: 250px;
        text-decoration: none;
        text-align: center;
        font-weight: bold;
        font-size: 120%;
    }
    .TemplateDisplayBox { margin: 5px; padding: 5px; border: 1px solid black; }
    .TemplateDisplayBox h2 { margin-bottom: 2px; font-size: 140%; font-weight: bold; }
    .TemplateDisplayBox p { margin-left: 10px; line-height: 140%; }
  </style>

  <script type="text/javascript">

      var PROFILE_CODE = 'SAME';
      var LOCATION_PROFILE_CODE = 'SAME';



      // old value was 'profile:CAP-CP:Event:0.3' ;


      // initial CAP data to populate alert with, customize as necessary
      var CAP_MESSAGE_NOINFO = { alert: { '@xmlns': 'urn:oasis:names:tc:emergency:cap:1.1',
          // customize identifier for each new alert
          identifier: 'undefined',
          sender: '{user not set}',
          sent: 'sent',
          status: 'status',
          msgType: 'type',
          source: 'IPAWS_CAP_GENERATOR',
          scope: 'Public',
          addresses: 'Addresses',
          code: 'NoCode',
          references: 'references'
      }
      };


      // initial CAP data to populate alert with, customize as necessary
      var CAP_MESSAGE = { alert: { '@xmlns': 'urn:oasis:names:tc:emergency:cap:1.1',
          // customize identifier for each new alert
          identifier: 'undefined',
          // customize the sender for this user
          sender: '{user not set}',
          sent: 'sent',
          status: 'status',
          msgType: 'type',
          source: 'IPAWS_CAP_GENERATOR',
          scope: 'Public',
          addresses: 'Addresses',
          code: 'NoCode',
          references: 'references',
          //code: 'profile:CAP-CP:0.3',
          info: [{
              language: 'en-US',
              category: 'category',
              event: 'event',
              responseType: 'none',
              urgency: 'urgency',
              severity: 'severity',
              certainty: 'certainty',
              audience: 'Unclassified',
              eventCode: { valueName: PROFILE_CODE, value: 'value' },
              //effective: 'effective',
              expires: 'expires',
              // customize the senderName for this user
              senderName: '{not set}',
              headline: 'headline',
              description: 'description',
              instruction: '',
              web: 'web',
              contact: 'contact',
              parameter: {},
              //parameter: {valueName: 'layer:CAPAN:eventLocation:point', value: 'value'},
              area: null
          }]
      }
      };

      // bounding box - left,bottom,right,top using lon,lat
      var MAP_DEFAULT_VIEW = '';

      // posting values
      //var IPAWS_FORWARDER_URL = ICNET_SERVER_URL+':23/IPAWSForwardService/PostData';
      //var IPAWS_FORWARDER_URL = ':8080/IPAWSForwardService/PostData';

      var IPAWS_FORWARDER_URL_CAP1_1 = IPAWS_FORWARDER_SERVER_URL + ':' + IPAWS_FORWARDER_SERVER_PORT + '/IPAWSForwardService/PostCAP11';
      var IPAWS_FORWARDER_URL_CAP1_2 = IPAWS_FORWARDER_SERVER_URL + ':' + IPAWS_FORWARDER_SERVER_PORT + '/IPAWSForwardService/PostCAP12';
      var IPAWS_FORWARDER_URL_CAP1_2_EAS = IPAWS_FORWARDER_SERVER_URL + ':' + IPAWS_FORWARDER_SERVER_PORT + '/IPAWSForwardService/PostCAP12?Profile=EAS';
      var IPAWS_FORWARDER_URL_CAP1_2_CMAS = IPAWS_FORWARDER_SERVER_URL + ':' + IPAWS_FORWARDER_SERVER_PORT + '/IPAWSForwardService/PostCAP12?Profile=CMAS';
      var IPAWS_FORWARDER_URL_CAP1_2_EAS_CMAS = IPAWS_FORWARDER_SERVER_URL + ':' + IPAWS_FORWARDER_SERVER_PORT + '/IPAWSForwardService/PostCAP12?Profile=EAS-CMAS';





      var MAIN_MENU_URL = 'index.html';


      // event list URL
      var EVENT_LIST_URL = ICNET_SERVER_URL+'/capform/events/get_events.txt';
      


      // area zone search URL
      var AREA_ZONE_URL = 'areas/get_areas.txt?code=none';

      // address search URL
      var ADDRESS_SEARCH_URL = 'address/address_search.txt?code=none';

      // ajax proxy url
      //var AJAX_PROXY_URL = 'A_go?code=wduyqb9jxzh6kif&url=';


      // global objects
      var locationMap, mainView, capPanel, areaZoneStore, areaSearchGrid;
      var previewWindow, postingTimeOut, postingResultText;

      // global vars for progress bar indicator
      var progressBarAmount = 0;
      // complete is 1 so divide by number of pages
      var progressBarIncrement = 0.50;

      // Path to the blank image should point to a valid location on your server
      Ext.BLANK_IMAGE_URL = 'post/ext-3.3.0/resources/images/default/s.gif';

      // turn on validation errors beside the field globally
      Ext.form.Field.prototype.msgTarget = 'side';

      // Tooltips on
      Ext.QuickTips.init();

      // Additional validation types
      Ext.form.VTypes.radius = function (v) {
          // checking seperately for 0 because it validates as !check_val = false
          if (v === '0') { return true; }
          var check_val = parseFloat(v);
          if (!check_val || check_val < 0 || check_val > 500) {
              return false;
          } else { return true; }
      };
      Ext.form.VTypes.radiusText = 'Between 0 and 500 is allowed';


      Ext.form.VTypes.geocode = function (v) {
          // checking seperately for 0 because it validates as !check_val = false
          if (v === '000000') { return true; }
          var check_val = parseFloat(v);
          if (!check_val || check_val < 0 || check_val > 999999) {
              return false;
          } else { return true; }
      };
      Ext.form.VTypes.geocodeText = 'Between 000000 and 999999 is allowed, PSSCCC';

      Ext.form.VTypes.sender = function (v) {
          // checking seperately for 0 because it validates as !check_val = false
          if (v.contains(' ')) { return false; }
          if (v.contains(',')) { return false; }
          if (v.contains('<')) { return false; }
          if (v.contains('>')) { return false; }
          if (v.contains('&')) { return false; }

          return true;
      };
      Ext.form.VTypes.senderText = 'No spaces, commas, angle brackets, or ampersands';

      Ext.form.VTypes.latlon = function (v) {
          // between -90 and 90 , -180 and 180 with maximum of 8 decimal places
          var regExp = /^(-?(90|(\d|[1-8]\d)(\.\d{1,8}){0,1}))\,{1}(-?(180|(\d|\d\d|1[0-7]\d)(\.\d{1,8}){0,1}))$/;
          return regExp.test(v);
      };
      Ext.form.VTypes.latlonText = 'Must be valid latitude,longitude';


      Ext.onReady(function () {

          locationMap = new OpenLayers.Map('locationMap', {
              numZoomLevels: 19,
              projection: new OpenLayers.Projection('EPSG:900913'),
              displayProjection: new OpenLayers.Projection('EPSG:4326'),
              units: 'm',
              maxResolution: 'auto',
              maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
              controls: [
              //new OpenLayers.Control.PanZoom(),
              //new OpenLayers.Control.ArgParser(),
              //new OpenLayers.Control.Attribution()
		]

          });

          var google_street = new OpenLayers.Layer.Google('Google Streets',
        { sphericalMercator: true });
          locationMap.addLayer(google_street);

          locationLayer = new OpenLayers.Layer.Vector('Location', { preFeatureInsert: clearSelection, onFeatureInsert: afterSetLocation });
          var sgcLayer = new OpenLayers.Layer.Vector('SGC');
          locationMap.addLayers([locationLayer, sgcLayer]);

          /*
          DeleteFeature = OpenLayers.Class(OpenLayers.Control, {
          initialize: function(layer, options) {
          OpenLayers.Control.prototype.initialize.apply(this, [options]);
          this.layer = layer;
          this.handler = new OpenLayers.Handler.Feature(
          this, layer, {click: this.clickFeature}
          );
          },
          clickFeature: function(feature) {
          // if feature doesn't have a fid, destroy it
          if(feature.fid == undefined) {
          this.layer.destroyFeatures([feature]);
          } else {
          feature.state = OpenLayers.State.DELETE;
          this.layer.events.triggerEvent("afterfeaturemodified", {feature: feature});
          feature.renderIntent = "select";
          this.layer.drawFeature(feature);
          }
          },
          setMap: function(map) {
          this.handler.setMap(map);
          OpenLayers.Control.prototype.setMap.apply(this, arguments);
          },
          CLASS_NAME: "OpenLayers.Control.DeleteFeature"
          })
          */
          /*
          SingleCircleFeature = OpenLayers.Class(OpenLayers.Control, {
          initialize: function(layer, options) {
          OpenLayers.Control.prototype.initialize.apply(this, [options]);
          this.layer = layer;
          this.handler = new OpenLayers.Handler.Feature(
          this, layer, {click: this.clickFeature}
          );
          },
          clickFeature: function(feature) {
          this.layer.destroyFeatures();
		
          },
          setMap: function(map) {
          this.handler.setMap(map);
          OpenLayers.Control.prototype.setMap.apply(this, arguments);
          },
          CLASS_NAME: "OpenLayers.Control.DeleteFeature"
          })
          */

          navControl = new OpenLayers.Control.Navigation({ title: 'Pan/Zoom' });
          editPanel = new OpenLayers.Control.Panel({ displayClass: 'editPanel' });

          //save_location_point

          editPanel.addControls([
        navControl,

        new OpenLayers.Control.DrawFeature(locationLayer, OpenLayers.Handler.Point,
            { displayClass: 'pointButton', title: 'Set circle center then enter radius',
                featureAdded: save_manual_circle
            }),



          //{sides: parseInt(this.value)}

		new OpenLayers.Control.DrawFeature(locationLayer,
                                            OpenLayers.Handler.RegularPolygon,
                                            { handlerOptions: { sides: 40 }, displayClass: 'circleButton', title: 'Draw circle', featureAdded: save_circle_selection }),


          /*
          new SingleCircleFeature(locationLayer,
          {displayClass: 'pointButton', title: 'Set Circle',
          featureAdded: save_location_point} ),
          */
		new OpenLayers.Control.DrawFeature(locationLayer, OpenLayers.Handler.Polygon,
            { displayClass: 'polygonButton', title: 'Set polygon',
                featureAdded: save_polygon_points
            })
          //new DeleteFeature(locationLayer, {displayClass: 'eraserButton',title: 'Eraser'})
          /*new OpenLayers.Control.SelectFeature([locationLayer],
          {displayClass: 'saveButton', title: 'Save Point', hover: false,
          onSelect: save_location_point} ) */
    ]);
          editPanel.defaultControl = navControl;
          locationMap.addControl(editPanel);


          var headerBox = new Ext.BoxComponent({
              region: 'north',
              height: 34,
              html: '<div id="headerTitleBlock">IPAWS CAP Generation Tool</div>' +
            '<div id="headerDetailBlock">' + '<pre><b>timezone:</b>' + timezone + '   ' +
			'<b>capform v</b>' + capformVersionNumber + '<br/><b>forwarder:</b>' + IPAWS_FORWARDER_SERVER_URL +
			'<b>   port:</b>' + IPAWS_FORWARDER_SERVER_PORT + '</pre></div>'
          });

          var progressBar = new Ext.ProgressBar({
              id: 'progressBar',
              width: 150,
              style: 'margin-left: 25px',
              text: 'Progress'
          });

          var cardNav = function (direction) {
              var card_panel = Ext.getCmp('cap-wizard-panel').getLayout();
              var current_card = card_panel.activeItem.id.split('card-')[1];

              // validate this card's form items first, if going forward
              if (direction > 0) {
                  var found_invalid_item = false;
                  card_panel.activeItem.cascade(function (item) {
                      if (item.isFormField) {
                          if (!item.validate()) { found_invalid_item = true; }
                      }
                  });
                  // validation check is performed here, comment out to bypass
                  //FIXME
                  if (found_invalid_item) { return; }
              }


              // special validation for area zones since its a grid
              if (current_card === '1') {
                  if (areaSearchGrid.doValidation) {
                      if (!areaSearchGrid.getSelectionModel().hasSelection()) {
                          alert('Area selection is required');
                          return;
                      }
                  }
              }


              // Forgive me for breaking the entire logic of the flow...
              var messageTypeString = Ext.getCmp('cap-message-type').value;
              if (messageTypeString == 'Cancel' && (direction > 0)) {
                  var next_card = 3;
                  card_panel.setActiveItem(next_card);
              }
              else if (messageTypeString == 'Cancel' && (direction < 0)) {

                  var next_card = 0;
                  card_panel.setActiveItem(next_card);
              }
              else {
                  var next_card = parseInt(current_card, 10) + direction;

                  card_panel.setActiveItem(next_card);

              }
              Ext.getCmp('cap-wizard-panel').doLayout();

              Ext.getCmp('card-prev').setDisabled(next_card == 0);
              // set to max number of cards
              Ext.getCmp('card-next').setDisabled(next_card == 3);
              if (direction === 1) {
                  progressBarAmount += progressBarIncrement;
              } else if (direction === -1) {
                  progressBarAmount -= progressBarIncrement;
              }
              progressBar.updateProgress(progressBarAmount);
          };


          var capCategoryCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Category</b>',
              name: 'cap-category',
              id: 'cap-category',
              allowBlank: false,
              width: 100,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              value: '',
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [['Geo', ''],
                ['Met', ''],
				['Security', ''],
				['Rescue', ''],
				['Fire', ''],
				['Health', ''],
				['Env', ''],
				['Transport', 'Beep Beep Im A Jeep'],
				['Infra', ''],
				['CBRNE', ''],
				['Other', ''],
				['Safety', '']]
              })

          });

          var capMessageTypeCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Message Type</b>',
              name: 'cap-message-type',
              id: 'cap-message-type',
              allowBlank: false,
              width: 100,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              value: 'Alert',
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [['Alert', ''],
                ['Update', ''],
				['Cancel', '']]
              })
          }
    );

          var capVersionCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Version</b>',
              name: 'cap-version',
              id: 'cap-version',
              allowBlank: false,
              width: 100,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              value: labelForCAP1_2,
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [[labelForCAP1_1, ''],
                [labelForCAP1_2, '']]
              }),
              listeners: { select: function () {
                  if (Ext.getCmp('cap-version').getValue() == labelForCAP1_1) {
                      //inputCAPCard.findById('cap-EASorg').setVisible(false);
                      //inputCAPCard.findById('cap-EASorg').allowBlank=true;

                      //inputCAPCard.findById('cap-cmamtext').setVisible(false);
                      Ext.getCmp('cap-cmamtext-checkbox').disable();
                      Ext.getCmp('cap-eas-checkbox').disable();
                      inputCAPCard.findById('cap-en-description').allowBlank = true;
                  }
                  else if (Ext.getCmp('cap-version').getValue() == labelForCAP1_2) {
                      //inputCAPCard.findById('cap-EASorg').setVisible(false);
                      //inputCAPCard.findById('cap-EASorg').allowBlank=true;

                      //inputCAPCard.findById('cap-cmamtext').setVisible(true);
                      Ext.getCmp('cap-cmamtext-checkbox').enable();
                      Ext.getCmp('cap-eas-checkbox').enable();

                      inputCAPCard.findById('cap-en-description').allowBlank = false;
                  }

              } 
              }

          });


          var capResponseTypeCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Response Type</b>',
              name: 'cap-response-type',
              id: 'cap-response-type',
              allowBlank: false,
              width: 150,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              value: 'None',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [['Shelter', 'Shelter'],
                   ['Evacuate', 'Evacuate'],
                   ['Prepare', 'Prepare'],
                   ['Execute', 'Execute'],
                   ['Avoid', 'Avoid'],
                   ['Monitor', 'Monitor'],
                   ['Assess', 'Assess'],
                   ['AllClear', 'AllClear'],
                   ['None', 'None']]
              })
          });


          var capScopeTypeCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Scope</b>',
              name: 'cap-scope',
              id: 'cap-scope',
              allowBlank: false,
              width: 150,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              value: 'Public',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [['Public', 'Public'],
                   ['Restricted', 'Restricted'],
				   ['Private', 'Private'],
                   ['None', 'None']]
              })
          });






          var statusCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Status</b>',
              name: 'cap-status',
              id: 'cap-status',
              allowBlank: false,
              width: 100,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'name',
              valueField: 'name',
              value: 'Test',
              tpl: '<tpl for="."><div ext:qtip="{tip}" class="x-combo-list-item">{name}</div></tpl>',
              store: new Ext.data.ArrayStore({
                  id: 0,
                  fields: ['name', 'tip'],
                  data: [['Actual', 'Actual Events'],
                ['Exercise', 'Exercises and other practice events'],
                ['Test', 'Test Alerts']]
              })
          });

          var eventCombo = new Ext.form.ComboBox({
              fieldLabel: '<b>Event</b>',
              name: 'cap-event',
              id: 'cap-event',
              allowBlank: false,
              width: 300,
              typeAhead: true,
              forceSelection: true,
              triggerAction: 'all',
              mode: 'local',
              displayField: 'e_name',
              valueField: 'value',
              tpl: new Ext.XTemplate(
            '<tpl for=".">',
            '<tpl if="this.group != \'\'"><div><b>{group}</b></div></tpl>',
            '<div ext:qtip="{e_tip}" class="x-combo-list-item">&nbsp;{e_name}</div>',
            '</tpl>'
        ),
              store: new Ext.data.Store({
                  proxy: new Ext.data.HttpProxy({ url: EVENT_LIST_URL, disableCaching: false }),
                  reader: new Ext.data.JsonReader({
                      root: 'events',
                      fields: ['group', 'e_name', 'e_tip', 'f_name', 'f_tip', 'value', 'category']
                  }),
                  autoLoad: true,
                  listeners: { exception: function () { alert('Unable to load Event Data'); } }
              }),
              listeners: { select: function () {
                  var et_index = this.store.find('value', this.getValue());
                  var et_record = this.store.getAt(et_index);
                  if (et_record !== null) {
                      // updating both english and french values, raw is no validation
                      inputCAPCard.findById('cap-en-headline').setRawValue(et_record.data.e_name +
                    ' alert issued'); // by ' + CAP_MESSAGE.alert.info[0].senderName + ' for (area)');

                  }
              } 
              }
          });

          var ExpirationSelector = new Ext.form.CompositeField({

              fieldLabel: 'Expires',
              width: 300,
              defaults: { flex: 1 },
              items: [
		{
		    xtype: 'combo',
		    name: 'cap-expires-interval',
		    id: 'cap-expires-interval',
		    value: 'Date & Time',
		    allowBlank: true,
		    width: 100,
		    typeAhead: true,
		    forceSelection: true,
		    triggerAction: 'all',
		    mode: 'local',
		    displayField: 'name',
		    valueField: 'interval',
		    tpl: '<tpl for="."><div class="x-combo-list-item">{name}&nbsp;</div></tpl>',
		    store: new Ext.data.ArrayStore({
		        id: 0,
		        fields: ['interval', 'name'],
		        data: [[0, 'Date & Time'],
					[1, 'after 1 Hour'],
					[6, 'after 6 Hours'],
				[12, 'after 12 Hours'],
				[24, 'after 24 Hours']]
		    }),
		    listeners: { select: function (combo, record, index) {

		        if (record.data.interval == 0) {
		            Ext.getCmp('cap-expires-dt').setVisible(true);
		            Ext.getCmp('cap-expires-dt').allowBlank = false;

		            Ext.getCmp('cap-expires-tm').setVisible(true);
		            Ext.getCmp('cap-expires-tm').allowBlank = false;
		        }
		        else {

		            Ext.getCmp('cap-expires-dt').setVisible(false);
		            Ext.getCmp('cap-expires-dt').allowBlank = true;

		            Ext.getCmp('cap-expires-tm').setVisible(false);
		            Ext.getCmp('cap-expires-tm').allowBlank = true;
		        }

		    }
		    }

		},
		{

		    name: 'cap-expires-dt',
		    id: 'cap-expires-dt',
		    width: 95,
		    xtype: 'datefield',
		    format: 'Y-m-d',
		    allowBlank: false,
		    listeners: { select: function () {
		        /*
		        var it_check = Ext.getCmp('cap-expires-interval').getValue();
		        if (it_check != 0) {
		        alert('Choose either a specified time OR an interval, not both');
		        }
		        */
		    } 
		    }
		},
		{
		    name: 'cap-expires-tm',
		    id: 'cap-expires-tm',
		    width: 60,
		    xtype: 'timefield',
		    format: 'H:i',
		    allowBlank: false,
		    listeners: { select: function () {
		        /*
		        var it_check = Ext.getCmp('cap-expires-interval').getValue();
		        if (it_check != 0) {
		        alert('Choose either a specified time OR an interval, not both');
		        }
		        */
		    } 
		    }
		}

		]
          });

          var CMAMTextSelector = new Ext.form.CompositeField({
              name: 'cap-cmamtext-selector',
              id: 'cap-cmamtext-selector',
              fieldLabel: '<b>CMAS</b>',
              width: 500,
              defaults: { flex: 1 },

              items: [
			{
			    xtype: 'checkbox', //defining the type of component  
			    fieldLabel: 'Enable CMAMtext', //assigning a label  
			    name: 'cap-cmamtext-checkbox', //and a "name" so we can retrieve it in the server...  
			    id: 'cap-cmamtext-checkbox', // ...when the form is sent 
			    hideLabel: false,
			    width: 40,
			    //lex:1,
			    //checked: true,

			    handler: function () {
			        if (this.checked) {

			            Ext.get('cap-cmamtext').setVisible(true);
			            Ext.get('cap-cmamtext-label').setVisible(true);
			        }
			        else {
			            Ext.get('cap-cmamtext').setVisible(false);
			            Ext.get('cap-cmamtext-label').setVisible(false);

			        }
			    },
			    listeners: {
			        enable: function () {
			        },
			        disable: function () {
			            Ext.getCmp('cap-cmamtext-checkbox').setValue(false);
			            Ext.getCmp('cap-eas-checkbox').setValue(false);
			        }
			    }

			},
			{
			    xtype: 'displayfield',
			    name: 'cap-cmamtext-label',
			    id: 'cap-cmamtext-label',
			    value: 'CMAM Text:',
			    //width: '80',
			    listeners: {
			        added: function (self, ownerCt, index) {
			            setTimeout(function foo(myClosure) {
			                Ext.get('cap-cmamtext-label').setVisible(false);
			            }
							, 1);

			        }
			    },
			    hideMode: 'visibility'
			},
			{
			    xtype: 'textfield',
			    fieldLabel: 'CMAMtext',
			    name: 'cap-cmamtext',
			    id: 'cap-cmamtext',
			    width: 375,
			    maxLength: 90,
			    value: '',
			    maxLengthText: '90 characters maximum',
			    //flex: 1,
			    listeners: {
			        added: function (self, ownerCt, index) {
			            //alert(true);
			            //self.hide();
			            //self.hide = true;
			            setTimeout(function foo(myClosure) {
			                Ext.get('cap-cmamtext').setVisible(false);
			            }
						, 1);
			            //self.setVisible(false);
			        }
			    },
			    hideMode: 'visibility'
			    //hideMode:'offsets',
			    //: true

			}

		]
          });




          var EASSelector = new Ext.form.CompositeField({
              name: 'cap-eas-selector',
              id: 'cap-eas-selector',
              fieldLabel: '<b>EAS</b>',
              width: 170,
              defaults: { flex: 1 },


              items: [
			{
			    xtype: 'checkbox', //defining the type of component  
			    fieldLabel: 'Enable CMAMtext', //assigning a label  
			    name: 'cap-eas-checkbox', //and a "name" so we can retrieve it in the server...  
			    id: 'cap-eas-checkbox', // ...when the form is sent 
			    hideLabel: false,
			    width: '40',

			    handler: function () {
			        if (this.checked) {
			            Ext.getCmp('cap-EASorg').allowBlank = false;
			            Ext.get('cap-EASorg').setVisible(true);
			            Ext.get('cap-EASorg-label').setVisible(true);

			        }
			        else {
			            Ext.get('cap-EASorg').setVisible(false);
			            Ext.get('cap-EASorg-label').setVisible(false);
			            Ext.getCmp('cap-EASorg').allowBlank = true;
			            Ext.getCmp('cap-EASorg').validate();
			        }

			    }

			},
			{
			    xtype: 'displayfield',
			    name: 'cap-EASorg-label',
			    id: 'cap-EASorg-label',
			    value: 'EAS Org:',
			    listeners: {
			        added: function (self, ownerCt, index) {
			            setTimeout(function foo(myClosure) {
			                Ext.get('cap-EASorg-label').setVisible(false);
			            }
							, 1);

			        }
			    },
			    hideMode: 'visibility'
			},
			{
			    xtype: 'textfield',
			    fieldLabel: 'EAS Org (EAS, CIV, WXR, PEP, etc)',
			    name: 'cap-EASorg',
			    id: 'cap-EASorg',
			    value: '',
			    width: '60',
			    //width: '10%',
			    blankText: 'Cannot be blank',

			    listeners: {
			        added: function (self, ownerCt, index) {
			            setTimeout(function foo(myClosure) {
			                Ext.get('cap-EASorg').setVisible(false);
			                Ext.get('cap-EASorg').allowBlank = true;
			            }
						, 1);

			        }


			    },
			    hideMode: 'visibility'


			}

		]
          });

          var EffectiveSelector = new Ext.form.CompositeField({

              fieldLabel: 'Effective',
              width: 300,
              defaults: { flex: 1 },
              items: [
		{
		    xtype: 'combo',
		    name: 'cap-effective-combo',
		    id: 'cap-effective-combo',
		    value: 'Now',

		    width: 100,
		    //typeAhead: true,
		    forceSelection: true,
		    triggerAction: 'all',
		    mode: 'local',
		    //editable: false,
		    displayField: 'name',
		    valueField: 'mode',
		    tpl: '<tpl for="."><div class="x-combo-list-item">{name}&nbsp;</div></tpl>',
		    store: new Ext.data.ArrayStore({
		        id: 0,
		        fields: ['mode', 'name'],
		        data: [[0, 'Now'],
					[1, 'Date & Time']]
		    }),
		    listeners: { select: function (combo, record, index) {

		        if (record.data.mode == 0) {
		            //Ext.getCmp('cap-effective-dt').setVisible(false);
		            Ext.getCmp('cap-effective-dt').hide();
		            Ext.getCmp('cap-effective-dt').allowBlank = true;
		            Ext.getCmp('cap-effective-dt').validate();

		            //Ext.getCmp('cap-effective-tm').setVisible(false);
		            Ext.getCmp('cap-effective-tm').hide();
		            Ext.getCmp('cap-effective-tm').allowBlank = true;
		            Ext.getCmp('cap-effective-tm').validate();
		            combo.findParentByType('container', false).doLayout();

		        }
		        else {
		            //Ext.getCmp('cap-effective-dt').setVisible(true);

		            Ext.getCmp('cap-effective-dt').show();
		            Ext.getCmp('cap-effective-dt').allowBlank = false;
		            //Ext.getCmp('cap-effective-dt').validate();

		            //Ext.getCmp('cap-effective-tm').setVisible(true);
		            Ext.getCmp('cap-effective-tm').show();
		            Ext.getCmp('cap-effective-tm').allowBlank = false;
		            //Ext.getCmp('cap-effective-tm').validate();
		            combo.findParentByType('container', false).doLayout();

		        }

		    }

		    }

		},
		{

		    name: 'cap-effective-dt',
		    id: 'cap-effective-dt',
		    width: 95,
		    xtype: 'datefield',
		    format: 'Y-m-d',
		    hidden: true,
		    allowBlank: true,
		    listeners: {
		        select: function () {

		        },
		        added: function (self, ownerCt, index) {
		            //self.setVisible(false);
		        },
		        afterrender: function (self) {
		            //self.hide();
		            //self.setVisible(false);
		        }
		    }
		},
		{
		    name: 'cap-effective-tm',
		    id: 'cap-effective-tm',
		    width: 60,
		    xtype: 'timefield',
		    format: 'H:i',
		    hidden: true,
		    allowBlank: true,
		    listeners: {
		        select: function () {

		        },
		        added: function (self, ownerCt, index) {
		            //self.setVisible(false);
		        },
		        afterrender: function (self) {
		            //self.hide();
		            //self.setVisible(false);
		        }

		    }
		}

		]
          });

          /*
          var intervalCombo = new Ext.form.ComboBox({
          fieldLabel: 'Or Expires',
          name: 'cap-expires-interval',
          id: 'cap-expires-interval',
          allowBlank: true,
          width: 100,
          typeAhead: true,
          forceSelection: true,
          triggerAction: 'all',
          mode: 'local',
          displayField: 'name',
          valueField: 'interval',
          tpl: '<tpl for="."><div class="x-combo-list-item">{name}&nbsp;</div></tpl>',
          store: new Ext.data.ArrayStore({
          id: 0,
          fields: ['interval', 'name'],
          data: [ [0, 'Date & Time'],
          [1, 'in 1 Hour'],
          [6, 'in 6 Hours'],
          [12, 'in 12 Hours'],
          [24, 'in 24 Hours']]
          }),
          listeners: {select: function(combo, record, index) {
		
          if (record.data.interval != 0) {
          var dt_check = Ext.get('cap-expires-dt').getValue();
          if (dt_check) {
          alert('Choose either a specified time OR an interval, not both');
          }
          }
		
          if (record.data.interval != 0) {
          var dt_check = Ext.get('cap-expires-dt').getValue();
          if (dt_check) {
          alert('Choose either a specified time OR an interval, not both');
          }
          }
          else{
			
          }
          }
          }});
          */

          var messageTypeCAPCard = new Ext.FormPanel({
              id: 'card-0',
              labelWidth: 100,
              bodyStyle: 'padding: 5px;',
              defaultType: 'textfield',
              items: [
			capVersionCombo,
				statusCombo,
				capMessageTypeCombo,

			{
			    fieldLabel: '<b>Sender</b>',
			    name: 'cap-en-sender',
			    id: 'cap-en-sender',
			    width: '50%',
			    allowBlank: false,
			    maxLength: 160,
			    value: 'Unknown_Sender',
			    vtype: 'sender'
			},
			{
			    fieldLabel: '<b>Addresses (including sender COG)</b>',
			    name: 'cap-en-addresses',
			    id: 'cap-en-addresses',
			    width: '50%',
			    allowBlank: true,
			    value: '999 100014 120038'
			},
			{
			    xtype: 'displayfield',
			    fieldLabel: '<b>References</b>',
			    name: 'cap-dummy',
			    id: 'cap-dummy',
			    width: 50,
			    value: ''

			},

			{
			    xtype: 'compositefield',
			    fieldLabel: 'Add Reference',
			    name: 'cap-reference-composite',
			    id: 'cap-reference-composite',
			    items: [

					{
					    xtype: 'textfield',
					    fieldLabel: '<b>Ref</b>',
					    name: 'cap-reference',
					    id: 'cap-reference',
					    width: 500,
					    //vtype: 'geocode',
					    value: exampleReference

					},
					{
					    xtype: 'button',
					    fieldLabel: 'add to list',
					    name: 'cap-add-reference',
					    id: 'cap-add-reference',
					    text: 'add to list',
					    handler: function () {
					        if (Ext.getCmp('cap-reference').validate() && Ext.getCmp('cap-reference').getValue() != '') {
					            var newReference = Ext.getCmp('cap-reference').getValue();
					            referenceArray.push(newReference);
					            Ext.getCmp('cap-reference-list').setValue(Ext.getCmp('cap-reference-list').value + newReference + '\n');
					            Ext.getCmp('cap-reference').setValue(exampleReference);

					        }

					    }
					}
				]
			},
			{
			    xtype: 'textarea',
			    fieldLabel: 'Reference List',
			    name: 'cap-reference-list',
			    id: 'cap-reference-list',
			    width: 516,
			    height: 60,
			    readOnly: true,
			    value: ''
			}


		]
          });




          var inputCAPCard = new Ext.FormPanel({
              id: 'card-1',
              labelWidth: 100,
              bodyStyle: 'padding: 5px;',
              defaultType: 'textfield',
              items: [capCategoryCombo, capResponseTypeCombo, eventCombo, CMAMTextSelector, EASSelector,
              /*
              capVersionCombo,
              statusCombo,
              capMessageTypeCombo,
				
              {
              fieldLabel: '<b>Sender</b>',
              name: 'cap-en-sender',
              id: 'cap-en-sender',
              width: '50%',
              allowBlank: false,
              maxLength: 160,
              value: 'Unknown Sender'
              }, */
        {
        xtype: 'radiogroup',
        fieldLabel: '<b>Urgency</b>',
        id: 'cap-urgency',
        allowBlank: false,
        width: 500,
        items: [{ boxLabel: 'Unknown', name: 'cap-urgency', inputValue: 'Unknown', checked: true },
                { boxLabel: 'Past', name: 'cap-urgency', inputValue: 'Past' },
                { boxLabel: 'Future', name: 'cap-urgency', inputValue: 'Future' },
                { boxLabel: 'Expected', name: 'cap-urgency', inputValue: 'Expected' },
                { boxLabel: 'Immediate', name: 'cap-urgency', inputValue: 'Immediate'}]
    }, {
        xtype: 'radiogroup',
        fieldLabel: '<b>Severity</b>',
        id: 'cap-severity',
        allowBlank: false,
        width: 500,
        items: [{ boxLabel: 'Unknown', name: 'cap-severity', inputValue: 'Unknown', checked: true },
                { boxLabel: 'Minor', name: 'cap-severity', inputValue: 'Minor' },
                { boxLabel: 'Moderate', name: 'cap-severity', inputValue: 'Moderate' },
                { boxLabel: 'Severe', name: 'cap-severity', inputValue: 'Severe' },
                { boxLabel: 'Extreme', name: 'cap-severity', inputValue: 'Extreme'}]
    }, {
        xtype: 'radiogroup',
        fieldLabel: '<b>Certainty</b>',
        id: 'cap-certainty',
        allowBlank: false,
        width: 500,
        items: [{ boxLabel: 'Unknown', name: 'cap-certainty', inputValue: 'Unknown', checked: true },
                { boxLabel: 'Unlikely', name: 'cap-certainty', inputValue: 'Unlikely' },
                { boxLabel: 'Possible', name: 'cap-certainty', inputValue: 'Possible' },
                { boxLabel: 'Likely', name: 'cap-certainty', inputValue: 'Likely' },
                { boxLabel: 'Observed', name: 'cap-certainty', inputValue: 'Observed'}]
    }, {
        fieldLabel: '<b>Headline</b>',
        name: 'cap-en-headline',
        id: 'cap-en-headline',
        width: '75%',
        minLength: 5,
        minLengthText: 'A good headline should say what and where',
        maxLength: 160,
        maxLengthText: 'CAP Headlines cannot be longer than 160 characters',
        blankText: 'Headline required',
        allowBlank: false
    }, {
        xtype: 'textarea',
        fieldLabel: 'Description',
        name: 'cap-en-description',
        id: 'cap-en-description',
        height: 80,
        width: '75%',
        value: 'n/a',
        allowBlank: false
    },
		{
		    xtype: 'textarea',
		    fieldLabel: 'Instruction',
		    name: 'cap-en-instruction',
		    id: 'cap-en-instruction',
		    width: '75%',
		    minLengthText: 'A good headline should say what and where',
		    maxLength: 2000,
		    height: 50,
		    maxLengthText: 'Too long',
		    allowBlank: true
		},
		{
		    fieldLabel: 'Contact',
		    name: 'cap-en-contact',
		    id: 'cap-en-contact',
		    width: '50%'
		}, {
		    fieldLabel: 'Web Link',
		    name: 'cap-en-web',
		    id: 'cap-en-web',
		    width: '50%',
		    allowBlank: true,
		    vtype: 'url'
		},
              /*
              {
              xtype: 'compositefield',
              fieldLabel: 'Expires at',
              width: 300,
              defaults: { flex: 1 },
              items: [{
              name: 'cap-expires-dt',
              id: 'cap-expires-dt',
              width: 95,
              xtype: 'datefield',
              format: 'Y-m-d',
              listeners: {select: function() {
              var it_check = Ext.getCmp('cap-expires-interval').getValue();
              if (it_check != 0) {
              alert('Choose either a specified time OR an interval, not both');
              }
              } }
              }, {
              name: 'cap-expires-tm',
              id: 'cap-expires-tm',
              width: 60,
              xtype: 'timefield',
              format: 'H:i',
              listeners: {select: function() {
              var it_check = Ext.getCmp('cap-expires-interval').getValue();
              if (it_check != 0) {
              alert('Choose either a specified time OR an interval, not both');
              }
              } }
				
              }]
              },*/

              //EffectiveSelector

		ExpirationSelector


		]
          });

          // create toolbar actions for the map
          var new_action;
          var map_toolbar_items = [];
          // zoom control
          new_action = new GeoExt.Action({
              text: 'Zoom to Default View',
              tooltip: 'Zoom to your saved Default Map View'
              //handler: zoom_to_default_view
          });
          map_toolbar_items.push(new_action);
          map_toolbar_items.push('-');

          var nav_control = new OpenLayers.Control.NavigationHistory();
          locationMap.addControl(nav_control);
          // navigation history - two "button" controls
          new_action = new GeoExt.Action({
              text: 'Previous View',
              tooltip: 'Zoom to previous view from history',
              control: nav_control.previous,
              disabled: true
          });
          map_toolbar_items.push(new_action);
          map_toolbar_items.push('-');
          new_action = new GeoExt.Action({
              text: 'Next View',
              tooltip: 'Zoom to next view in history',
              control: nav_control.next,
              disabled: true
          });
          map_toolbar_items.push(new_action);
          map_toolbar_items.push('-');

          // address search box for remote geocode searches
          var addressSearchCombo = new Ext.form.ComboBox({
              width: 200,
              listWidth: 300,
              // minimum characters before search query is sent
              minChars: 6,
              // hide trigger of the combo
              hideTrigger: true,
              forceSelection: true,
              loadingText: 'Searching...',
              emptyText: 'Address Search',
              allowBlank: true,
              displayField: 'address',
              store: new Ext.data.Store({
                  proxy: new Ext.data.HttpProxy({
                      url: ADDRESS_SEARCH_URL,
                      method: 'GET',
                      disableCaching: false
                  }),
                  reader: new Ext.data.JsonReader({
                      root: 'results',
                      fields: ['address', 'lat', 'lon']
                  })
              }),
              listeners: { select: function (combo, record) {
                  var address_xy = new OpenLayers.LonLat(record.data.lon, record.data.lat);
                  address_xy = address_xy.transform(new OpenLayers.Projection('EPSG:4326'),
                locationMap.getProjectionObject());
                  var address_point = new OpenLayers.Geometry.Point(address_xy.lon, address_xy.lat);
                  var address_feature = new OpenLayers.Feature.Vector(address_point, null,
                { fillColor: 'red', fillOpacity: 1, strokeColor: 'red', strokeOpacity: 1,
                    pointRadius: 6, label: record.data.address, labelYOffset: 15
                });
                  locationMap.getLayersByName('Location')[0].addFeatures([address_feature]);
                  locationMap.setCenter(address_xy, 14);
              } 
              }
          });
          map_toolbar_items.push(addressSearchCombo);


          // create map panel
          var locationMapPanel = new GeoExt.MapPanel({
              collapsible: false,
              style: 'margin-bottom: 5px;',
              //TODO: resizable?
              height: 500,
              map: locationMap,
              bbar: map_toolbar_items
          });
          /*
          var areaSearchCombo = new Ext.form.ComboBox({
          fieldLabel: '<b>Search</b>',
          width: 100,
          typeAhead: true,
          forceSelection: true,
          triggerAction: 'all',
          mode: 'local',
          displayField: 'name',
          valueField: 'value',
          store: new Ext.data.ArrayStore({
          id: 0,
          fields: ['value', 'name'],
          data: [ [5, '5 KM'], [50, '50 KM'], [100, '100 KM'] ]
          }),
          listeners: {select: existing_area_search}
          });
          */

          areaZoneStore = new GeoExt.data.FeatureStore({
              layer: sgcLayer,
              fields: [
            { name: 'e_name', type: 'string' },
            { name: 'f_name', type: 'string' },
            { name: 'sgc', type: 'string' }
        ],
              proxy: new GeoExt.data.ProtocolProxy({
                  protocol: new OpenLayers.Protocol.HTTP({
                      url: AREA_ZONE_URL,
                      format: new OpenLayers.Format.GeoJSON({
                          internalProjection: locationMap.getProjectionObject(),
                          externalProjection: new OpenLayers.Projection('EPSG:4326')
                      })
                  })
              }),
              autoLoad: false
          });

          areaSearchGrid = new Ext.grid.GridPanel({
              hideHeaders: true,
              fieldLabel: '<b>Select</b>',
              name: 'cap-area-zones',
              id: 'cap-area-zones',
              width: 250,
              height: 75,
              doValidation: false,
              store: areaZoneStore,
              columns: [{
                  header: "Name",
                  width: 245,
                  dataIndex: "e_name"
              }],
              sm: new GeoExt.grid.FeatureSelectionModel()
          });

          locationCAPCard = new Ext.FormPanel({
              id: 'card-2',
              labelWidth: 100,
              items: [
			locationMapPanel,
			{
			    xtype: 'textfield',
			    fieldLabel: '<b>Description</b>',
			    name: 'cap-en-area-description',
			    id: 'cap-en-area-description',
			    width: '90%',
			    maxLength: 100,
			    blankText: 'An area description is required',
			    value: 'none',
			    allowBlank: false
			},


			{
			    xtype: 'textfield',
			    fieldLabel: 'Area Info',
			    name: 'cap-area-reminder',
			    id: 'cap-area-reminder',
			    width: '90%',
			    value: '',
			    blankText: 'Use the map tools to select an area',
			    allowBlank: true,
			    readOnly: true
			},


			{
			    xtype: 'compositefield',
			    fieldLabel: '<b>Add Geocode</b>',
			    name: 'cap-geocode-composite',
			    id: 'cap-geocode-composite',
			    items: [

					{
					    xtype: 'textfield',
					    fieldLabel: '<b>Geocodes</b>',
					    name: 'cap-geocode',
					    id: 'cap-geocode',
					    width: 50,
					    maxLength: 6,
					    minLength: 6,
					    vtype: 'geocode',
					    value: '036005'
					    //blankText: 'Use the PSSCCC format, 000000 for the full US',

					},
					{
					    xtype: 'button',
					    fieldLabel: 'add to list',
					    name: 'cap-add-geocode',
					    id: 'cap-add-geocode',
					    text: 'add to list',
					    handler: function () {
					        if (Ext.getCmp('cap-geocode').validate() && Ext.getCmp('cap-geocode').getValue() != '') {

					            geocodeArrays.push(Ext.getCmp('cap-geocode').getValue());
					            Ext.getCmp('cap-geocode-list').setValue(Ext.getCmp('cap-geocode-list').value + Ext.getCmp('cap-geocode').getValue() + '\n');
					            Ext.getCmp('cap-geocode').setValue('');

					        }

					    }
					}
				]
			},

			{
			    xtype: 'textarea',
			    fieldLabel: '<b>Geocode List</b>',
			    name: 'cap-geocode-list',
			    id: 'cap-geocode-list',
			    width: 70,
			    height: 60,
			    readOnly: true,
			    value: ''
			}


		]
          });

          /*
          {
          xtype: 'fieldset',
			
          style: 'margin-left: 15px; padding: 5px;',
			
          title: 'Geographic Code',
          id: 'geocode',
          items: [{
          xtype: 'textfield',
          fieldLabel: '<b>Geocode</b>',
          name: 'cap-geocode',
          id: 'cap-geocode',
          width: 50,
          vtype: 'geocode',
          value: '000000',
          blankText: 'Use the PSSCCC format, 000000 for the full US',
          allowBlank: false
          }],
          listeners: {
				
          }
          }
          */

          //	]
          // });

          var vkeyboard_plugin = new Ext.ux.plugins.VirtualKeyboard();

          var optionalCAPCard = new Ext.FormPanel({
              id: 'card-100',
              labelWidth: 80,
              bodyStyle: 'padding: 10px;',
              items: [{
                  xtype: 'displayfield',
                  hideLabel: true,
                  html: '<div style="margin-bottom: 15px;"><b>Multiple Languages</b> (Optional)</div>'
              }, {
                  xtype: 'fieldset',
                  checkboxToggle: true,
                  collapsed: true,
                  title: 'Add French Content?',
                  id: 'cap-add-french',
                  defaultType: 'textfield',
                  items: [{
                      fieldLabel: '<b>Headline</b>',
                      name: 'cap-fr-headline',
                      id: 'cap-fr-headline',
                      anchor: '75%',
                      minLengthText: 'A good headline should say what and where',
                      maxLength: 160,
                      maxLengthText: 'CAP Headlines cannot be longer than 160 characters',
                      blankText: 'Requires a headline value',
                      keyboardConfig: { language: 'French', showIcon: true },
                      plugins: vkeyboard_plugin
                  }, {
                      xtype: 'textarea',
                      fieldLabel: 'Description',
                      name: 'cap-fr-description',
                      id: 'cap-fr-description',
                      height: 80,
                      anchor: '75%',
                      keyboardConfig: { language: 'French', showIcon: true },
                      plugins: vkeyboard_plugin
                  }, {
                      fieldLabel: 'Contact',
                      name: 'cap-fr-contact',
                      id: 'cap-fr-contact',
                      anchor: '50%',
                      keyboardConfig: { language: 'French', showIcon: true },
                      plugins: vkeyboard_plugin
                  }, {
                      fieldLabel: 'Web Link',
                      name: 'cap-fr-web',
                      id: 'cap-fr-web',
                      width: '50%',
                      allowBlank: true,
                      vtype: 'url'
                  }, {
                      fieldLabel: '<b>Area</b>',
                      name: 'cap-fr-area-description',
                      id: 'cap-fr-area-description',
                      anchor: '35%',
                      maxLength: 100,
                      blankText: 'An area description is required',
                      keyboardConfig: { language: 'French', showIcon: true },
                      plugins: vkeyboard_plugin
                  }],
                  listeners: {
                      expand: function () {
                          // enable validation of french values
                          optionalCAPCard.findById('cap-fr-headline').allowBlank = false;
                          optionalCAPCard.findById('cap-fr-headline').minLength = 5;
                          if (!locationCAPCard.findById('areaCreateSet').collapsed) {
                              optionalCAPCard.findById('cap-fr-area-description').allowBlank = false;
                          } 
                      },
                      collapse: function () {
                          // disable validation of french values when not using
                          optionalCAPCard.findById('cap-fr-headline').allowBlank = true;
                          optionalCAPCard.findById('cap-fr-headline').minLength = null;
                          optionalCAPCard.findById('cap-fr-area-description').allowBlank = true;
                      }
                  }
              }]
          });

          var postCAPCard = new Ext.Panel({
              id: 'card-3',
              html: '<div class="postingCard" id="postingBox"><h1>Ready to Post</h1>' +
              //'<a href="javascript:{alert('x');}" style="color: green;">Download CAP Alert</a>'+
            '</div>',
              listeners: { activate: function (panel) {
                  generatedXML = generate_CAP_XML();

                  document.getElementById('postingBox').innerHTML = "" +
					CAP_Display_Template_Mini.apply(generatedXML[1]) +
					'<a href="javascript:preview_CAP_XML();" style="color: grey;">Preview CAP XML</a>' +
					'<a href="javascript:post_CAP_alert();" style="color: green;">Post CAP Alert</a>';
              }
              }
          });

          //defaultCards = [ inputCAPCard, locationCAPCard, postCAPCard ];
          defaultCards = [messageTypeCAPCard, inputCAPCard, locationCAPCard, postCAPCard];
          cancelMessageCards = [messageTypeCAPCard, postCAPCard];

          capPanel = new Ext.Panel({
              id: 'cap-wizard-panel',
              //title: 'New CAP Alert',
              region: 'center',
              layout: 'card',
              activeItem: 0,
              bodyStyle: 'padding: 10px;',
              defaults: { border: false, autoScroll: true },
              tbar: [
              //progressBar,

            '->',
            { text: '<b>Start Over</b>',
                icon: 'post/img/abort.png',
                handler: function () { javascript: location.reload(true) } 
            }

        ],
              bbar: new Ext.Toolbar({ items: [
                  /*
                  { id: 'card-reset',
                  text: '<span style="font-weight: bold; font-size: 130%;">Next</span>',
                  icon: 'post/img/next-page.png',
                  iconAlign: 'left',
                  handler: cardNav.createDelegate(this, [1]) },
                  { xtype: 'tbspacer', autoWidth:true, 
                  layoutConfig: {
                  align: 'left'
                  }
                  },*/
            {id: 'card-prev',
            text: '<span style="font-weight: bold; font-size: 130%;">Back</span>',
            icon: 'post/img/previous-page.png',
            handler: cardNav.createDelegate(this, [-1]),
            disabled: true
        },
            { xtype: 'tbspacer', width: 150 },
            { id: 'card-next',
                text: '<span style="font-weight: bold; font-size: 130%;">Next</span>',
                icon: 'post/img/next-page.png',
                iconAlign: 'right',
                handler: cardNav.createDelegate(this, [1])
            }
        ], buttonAlign: 'center'
              }),
              // the panels (or "cards") within the layout
              //items: [ inputCAPCard, locationCAPCard, optionalCAPCard, postCAPCard ]
              items: defaultCards
          });

          // main layout view, uses entire browser viewport
          mainView = new Ext.Viewport({
              layout: 'border',
              items: [headerBox, capPanel]
          });


          //Ext.get('cap-status').focus();

          // set map to show default location
          locationMap.setCenter(new OpenLayers.LonLat(-73.986053, 40.682721).transform(
        new OpenLayers.Projection('EPSG:4326'), locationMap.getProjectionObject()), 4 + 6);

      });


      function zoom_to_default_view() {
          if (MAP_DEFAULT_VIEW) {
              var default_view_bounds = new OpenLayers.Bounds.fromString(MAP_DEFAULT_VIEW);
              default_view_bounds.transform(new OpenLayers.Projection('EPSG:4326'),
            locationMap.getProjectionObject());
              locationMap.zoomToExtent(default_view_bounds);
          }
      }

      function save_location_point(feature) {
          if (feature.geometry) {

              var new_point = new OpenLayers.Geometry.Point(feature.geometry.x, feature.geometry.y);
              new_point.transform(locationMap.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));
              //var location_box = document.getElementById('cap-location');


              point_location = new_point.y.toPrecision(7) + ',' + new_point.x.toPrecision(7);
              //location_box.value = point_location;

              locationCAPCard.findById('cap-area-reminder').setRawValue('Point (' + point_location + ')');
              locationCAPCard.findById('cap-area-reminder').validate();
          }
      }

      function save_manual_circle(feature) {
          if (feature.geometry) {

              var new_point = new OpenLayers.Geometry.Point(feature.geometry.x, feature.geometry.y);
              new_point.transform(locationMap.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));

              point_location = new_point.y.toPrecision(7) + ',' + new_point.x.toPrecision(7);

              selection_circle_radius = parseFloat(prompt("Enter circle radius in kilometers", "100"));
              selection_circle_radius = selection_circle_radius.toPrecision(6);
              if (isNaN(selection_circle_radius)) {
                  selection_circle_radius = 1.0;
              }
              if (selection_circle_radius <= 0) {
                  selection_circle_radius = 0.01;
              }



              var circle_origin_xy = new OpenLayers.Geometry.Point(feature.geometry.x, feature.geometry.y);
              locationLayer.destroyFeatures();
              var circle_feature = new OpenLayers.Geometry.Polygon.createRegularPolygon(circle_origin_xy, selection_circle_radius * 1000.0, 40, 0); //origin,radius in meters,sides,rotation
              locationLayer.addFeatures([new OpenLayers.Feature.Vector(circle_feature)]);

              polygon_string = '';

              locationCAPCard.findById('cap-area-reminder').setRawValue('Circle [Center=' + point_location + '  Radius=' + selection_circle_radius + 'km]');
              locationCAPCard.findById('cap-area-reminder').validate();

          }
      }

      function save_circle_selection(feature) {
          if (feature.geometry) {

              var limits = feature.geometry.getBounds();
              selection_circle_radius = (limits.getWidth() / 2) / 1000.0;
              selection_circle_radius = selection_circle_radius.toPrecision(6);

              var new_point = feature.geometry.getCentroid();
              new_point.transform(locationMap.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));
              point_location = new_point.y.toPrecision(7) + ',' + new_point.x.toPrecision(7);
              polygon_string = '';

              locationCAPCard.findById('cap-area-reminder').setRawValue('Circle [Center=' + point_location + '  Radius=' + selection_circle_radius + 'km]');
              locationCAPCard.findById('cap-area-reminder').validate();


          }
      }


      function save_polygon_points(feature) {
          if (feature.geometry) {

              var out_options = {
                  'internalProjection': locationMap.getProjectionObject(),
                  'externalProjection': new OpenLayers.Projection("EPSG:4326")
              };

              var formatter = new OpenLayers.Format.GeoJSON(out_options);

              var json_polygon = JSON.parse(formatter.write(feature, false));




              point_location = '';
              selection_circle_radius = '';

              var points = json_polygon["geometry"]["coordinates"][0]
              for (var i = 0; i < points.length; i++) {
                  var obj = points[i] + '';
                  var coords = obj.split(",");
                  var reversed = coords[1] + ',' + coords[0];
                  //alert(obj+' is now '+reversed);
                  polygon_string = polygon_string + reversed;
                  if (i < (points.length - 1)) {
                      polygon_string = polygon_string + ' ';
                  }
              }


              var centroid = feature.geometry.getCentroid();
              centroid.transform(locationMap.getProjectionObject(), new OpenLayers.Projection('EPSG:4326'));
              point_location = centroid.y.toPrecision(7) + ',' + centroid.x.toPrecision(7);
              locationCAPCard.findById('cap-area-reminder').setRawValue('Polygon [Center=' + point_location + '  Points=' + polygon_string + ']');
              locationCAPCard.findById('cap-area-reminder').validate();
          }
      }



      function clearSelection(feature) {
          locationLayer.destroyFeatures();
      }

      function afterSetLocation(feature) {
          //navControl.activate();
          editPanel.activateControl(navControl);
      }
      /*
      function existing_area_search(){
      var point_value = document.getElementById('cap-location').value;
      if (!point_value) { alert('Location Point Missing'); return; }
      // options.url is what's used for actual loading
      var new_url = AREA_ZONE_URL + '&point=' + point_value + '&radius=' + this.value;
      areaZoneStore.proxy.protocol.options.url = new_url;
      areaZoneStore.load();
      }
      */

      function cloneObject(obj) {
          if (obj === null || typeof (obj) !== 'object') { return obj; }
          var temp = new obj.constructor(); // changed (twice)
          var key = null;
          for (key in obj) {
              temp[key] = cloneObject(obj[key]);
          }
          return temp;
      }

      function XmlEncode(text) {
          // encode XML special characters as entities instead
          text = text.replace(/\&/g, '&amp;');
          text = text.replace(/</g, '&lt;');
          text = text.replace(/>/g, '&gt;');
          return text;
      }



      function generate_CAP_XML() {
          var cap_message;
          var version = Ext.getCmp('cap-version').value;
          var cmas_enabled = Ext.getCmp('cap-cmamtext-checkbox').checked;
          var eas_enabled = Ext.getCmp('cap-eas-checkbox').checked;




          if (Ext.getCmp('cap-message-type').getRawValue() != "Cancel") {
              if (version == labelForCAP1_1) {
                  cap_message = generate_CAP_XML_v1dot1();

                  // remove the code element, it is not needed for CAP1.1
                  delete cap_message.alert['code'];

              }
              else if (version == labelForCAP1_2) {
                  cap_message = generate_CAP_XML_v1dot2();

                  if (eas_enabled) {
                      var eas_org_value = Ext.get('cap-EASorg').getValue();
                      cap_message.alert.info.parameter.push({ valueName: 'EAS-ORG', value: eas_org_value });
                  }

                  if (cmas_enabled) {
                      var cmamtext = Ext.getCmp('cap-cmamtext').getValue();
                      if (cmamtext != '') {
                          cap_message.alert.info.parameter.push({ valueName: 'CMAMtext', value: cmamtext });
                      }
                  }


                  if (!cmas_enabled && !eas_enabled) {
                      delete cap_message.alert.info.parameter;
                  }
                  else if (cmas_enabled && !eas_enabled) {

                  }
                  else if (!cmas_enabled && eas_enabled) {

                  }
                  else if (cmas_enabled && eas_enabled) {

                  }
              }
              else {
                  alert('version not Possible');
              }
          }
          else { // generateInfoNode==false

              if (version == labelForCAP1_1) {
                  cap_message = generate_CAP_XML_v1dot1_NoInfo();

                  // remove the code element, it is not needed for CAP1.1
                  delete cap_message.alert['code'];

              }
              else if (version == labelForCAP1_2) {
                  cap_message = generate_CAP_XML_v1dot2_NoInfo();
              }
          }

          var new_xml = xmlJsonClass.json2xml(cap_message, '');
          new_xml = formatXml(new_xml);

          WriteLog('Info', 'generate_CAP_XML: XML=' + new_xml); 

          return [new_xml, cap_message];
      }

      // patch the 1.1 into a 1.2
      function generate_CAP_XML_v1dot2() {
          var cap_message_1 = generate_CAP_XML_v1dot1();

          cap_message_1.alert['@xmlns'] = 'urn:oasis:names:tc:emergency:cap:1.2';
          cap_message_1.alert.code = "IPAWSv1.0";
          cap_message_1.alert.info.parameter = new Array();




          //cap_message_1.alert.info.responseType = Ext.get('cap-response-type').getValue();

          return cap_message_1;
      }

      function generate_CAP_CML_references(message) {
          // GenerateReferences string
          if (referenceArray.length > 0) {
              var referencesString = '';
              for (i = 0; i < referenceArray.length; i++) {
                  referencesString += referenceArray[i];
                  if (i < referenceArray.length - 1) {
                      referencesString += ' ';
                  }
              }
              message.alert.references = referencesString;
          }
          else {
              delete message.alert.references
          }
      }

      function generate_CAP_XML_v1dot1_NoInfo() {

          if (!CAP_MESSAGE_NOINFO) { alert('Unable to load CAP XML Message'); }
          // cloning CAP_MESSAGE each time required for cases where a user
          // goes back and add/removes values after doing a preview which
          // results in a modified CAP_MESSAGE being used to build the post XML
          var new_message = cloneObject(CAP_MESSAGE_NOINFO);

          var sent_time = new Date();

          generate_CAP_CML_references(new_message);

          // set message type:
          new_message.alert.msgType = Ext.getCmp('cap-message-type').value;

          // using Ext extensions to Date for formatting
          new_message.alert.sent = sent_time.format('Y-m-d\\TH:i:s') + timezone;

          new_message.alert.status = Ext.get('cap-status').getValue();
          new_message.alert.sender = Ext.get('cap-en-sender').getValue();

          var addresses = Ext.get('cap-en-addresses').getValue();
          if (addresses != '') {
              new_message.alert.addresses = addresses;
          }
          else {
              delete new_message.alert.addresses;
          }

          //make the msgid unique based on the date it was sent
          new_message.alert.identifier = 'IPAWS-CAP-Generator-' + sent_time.getTime(); //sent_time.format('Y-m-d\\TH-i');

          return new_message;
      }

      function generate_CAP_XML_v1dot2_NoInfo() {

          var cap_message_1 = generate_CAP_XML_v1dot1_NoInfo();

          cap_message_1.alert['@xmlns'] = 'urn:oasis:names:tc:emergency:cap:1.2';
          cap_message_1.alert.code = "IPAWSv1.0";

          return cap_message_1;
      }


      function generate_CAP_XML_v1dot1() {
          if (!CAP_MESSAGE) { alert('Unable to load CAP XML Message'); }
          // cloning CAP_MESSAGE each time required for cases where a user
          // goes back and add/removes values after doing a preview which
          // results in a modified CAP_MESSAGE being used to build the post XML
          var new_message = cloneObject(CAP_MESSAGE);



          //TODO: consider using only UTC for this sent date??
          var sent_time = new Date();

          generate_CAP_CML_references(new_message);

          //var effective_combo = Ext.getCmp('cap-effective-combo');
          //var effective_index =  effective_combo.store.find('name', effective_combo.getValue());
          //var effective_record = effective_combo.store.getAt(effective_index);
          //if(effective_record.data.mode == 0){

          // No effective Field needed for current UI
          /*
          var effective_time = new Date();
          if(Ext.getCmp('cap-effective-combo').getRawValue()=='Now'){
          new_message.alert.info[0].effective = effective_time.format('Y-m-d\\TH:i:ss')+timezone;
          }
          else{
          //alert(Ext.getCmp('cap-effective-combo').getRawValue());
          var effective_dt = Ext.get('cap-effective-dt').getValue();
          var effective_tm = Ext.get('cap-effective-tm').getValue();
          var dateparts = effective_dt.match(/(\d+)/g);
          effective_time.setUTCFullYear(dateparts[0]);
          effective_time.setUTCMonth(dateparts[1]-1);
          effective_time.setUTCDate(dateparts[2]);
		
          var timeparts = effective_tm.match(/(\d+)/g);
          effective_time.setUTCHours(timeparts[0]);
          effective_time.setUTCMinutes(timeparts[1]);
          effective_time.setUTCSeconds(0);
          effective_time.setUTCMilliseconds(0);
		
		
          var effective_time_ms = effective_time.getTime();
          effective_time.setTime(effective_time_ms - timezone_ms);
		
          new_message.alert.info[0].effective = effective_dt + 'T' + effective_tm + ':00' + timezone;//sent_time.format('P');
          }
          */

          // set message type:
          new_message.alert.msgType = Ext.getCmp('cap-message-type').value;




          // using Ext extensions to Date for formatting
          new_message.alert.sent = sent_time.format('Y-m-d\\TH:i:s') + timezone;
          new_message.alert.status = Ext.get('cap-status').getValue();
          new_message.alert.info[0].senderName = Ext.get('cap-en-sender').getValue();
          new_message.alert.info[0].responseType = Ext.get('cap-response-type').getValue();
          new_message.alert.sender = Ext.get('cap-en-sender').getValue(); //'IPAWS_CAP_Generation_Tool';

          var addresses = Ext.get('cap-en-addresses').getValue();
          if (addresses != '') {
              new_message.alert.addresses = addresses;
          }
          else {
              delete new_message.alert.addresses;
          }

          //make the msgid unique based on the date it was sent
          //new_message.alert.identifier = 'IPAWS-CAP-Generator-'+sent_time.format('Y-m-d\\TH-i');
          new_message.alert.identifier = 'IPAWS-CAP-Generator-' + sent_time.getTime();

          // info_block order for english users
          var en_info = new_message.alert.info[0];


          var et_combo = Ext.getCmp('cap-event');
          if (!et_combo) { alert('Unable to create CAP XML - Event Data Missing'); }
          var et_index = et_combo.store.find('value', et_combo.getValue());
          var et_record = et_combo.store.getAt(et_index);
          if (et_record !== null) {
              en_info.event = et_record.data.e_name;

              // category is manually set now
              //en_info.category = et_record.data.category;

              // set message category manually
              en_info.category = Ext.getCmp('cap-category').value;

              en_info.eventCode.value = et_record.data.value;

          }
          en_info.urgency = Ext.getCmp('cap-urgency').getValue().getGroupValue();
          en_info.severity = Ext.getCmp('cap-severity').getValue().getGroupValue();
          en_info.certainty = Ext.getCmp('cap-certainty').getValue().getGroupValue();
          var expires_dt = Ext.get('cap-expires-dt').getValue();
          var expires_tm = Ext.get('cap-expires-tm').getValue();
          var expires_it = Ext.getCmp('cap-expires-interval').getValue();
          if (expires_dt && expires_tm) {
              en_info.expires = expires_dt + 'T' + expires_tm + ':00' + timezone;

          } else if (expires_it != 0) {

              var expires_time = new Date();
              var expires_epoch = expires_time.getTime(); //effective_time.getTime(); // it is an offeset from EFFECTIVE time, not the current time
              expires_epoch += parseInt(expires_it) * 3600000;
              expires_time.setTime(expires_epoch);
              en_info.expires = expires_time.format('Y-m-d\\TH:i:s') + timezone;

          } else {
              delete en_info.expires;

          }

          en_info.headline = XmlEncode(Ext.get('cap-en-headline').getValue());
          en_info.headline = XmlEncode(Ext.get('cap-en-headline').getValue());


          if (Ext.get('cap-en-instruction').getValue() != '') {
              en_info.instruction = XmlEncode(Ext.get('cap-en-instruction').getValue());
          }
          else {
              delete en_info.instruction;
          }

          // clean out defaults for area that the user didn't fill in
          //en_info.headline = en_info.headline.replace(' for (area)', '');

          var en_description = Ext.get('cap-en-description').getValue();
          if (en_description) {
              en_info.description = XmlEncode(en_description);
          } else { delete en_info.description; }

          var en_contact = Ext.get('cap-en-contact').getValue();
          if (en_contact) {
              en_info.contact = XmlEncode(en_contact);
          } else { delete en_info.contact; }

          var en_web = Ext.get('cap-en-web').getValue();
          if (en_web) {
              en_info.web = en_web;
          } else { delete en_info.web; }


          if (selection_circle_radius != '') {
              var circle_val = point_location + ' ' + selection_circle_radius;
              en_info.area = { areaDesc: XmlEncode(Ext.get('cap-en-area-description').getValue()),
                  circle: circle_val, geocode: {}
              };


          }
          else if (polygon_string != '') {
              en_info.area = { areaDesc: XmlEncode(Ext.get('cap-en-area-description').getValue()),
                  polygon: polygon_string, geocode: {}
              };
          }
          else { //no circle or polygon
              en_info.area = { areaDesc: XmlEncode(Ext.get('cap-en-area-description').getValue()), geocode: {} };
          }

          en_info.area.geocode = new Array();
          for (i = 0; i < geocodeArrays.length; i++) {
              en_info.area.geocode.push({ valueName: LOCATION_PROFILE_CODE, value: geocodeArrays[i] });
          }

          if (geocodeArrays.length == 0) {
              delete en_info.area.geocode;
          }

          new_message.alert.info = en_info;
          return new_message;

          //var new_xml = xmlJsonClass.json2xml(new_message, '');
          //new_xml = formatXml(new_xml);
          //new_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + new_xml;

          //return [new_xml, new_message];
      }

      function formatXml(xml) {
          var reg = /(>)(<)(\/*)/g;
          var wsexp = / *(.*) +\n/g;
          var contexp = /(<.+>)(.+\n)/g;
          xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
          var formatted = '';
          var lines = xml.split('\n');
          var indent = 0;
          var lastType = 'other';
          // 4 types of tags - single, closing, opening, other (text, doctype, comment) - 4*4 = 16 transitions 
          var transitions = {
              'single->single': 0,
              'single->closing': -1,
              'single->opening': 0,
              'single->other': 0,
              'closing->single': 0,
              'closing->closing': -1,
              'closing->opening': 0,
              'closing->other': 0,
              'opening->single': 1,
              'opening->closing': 0,
              'opening->opening': 1,
              'opening->other': 1,
              'other->single': 0,
              'other->closing': -1,
              'other->opening': 0,
              'other->other': 0
          };
          for (var i = 0; i < lines.length; i++) {
              var ln = lines[i];
              var single = Boolean(ln.match(/<.+\/>/)); // is this line a single tag? ex. <br />
              var closing = Boolean(ln.match(/<\/.+>/)); // is this a closing tag? ex. </a>
              var opening = Boolean(ln.match(/<[^!].*>/)); // is this even a tag (that's not <!something>)
              var type = single ? 'single' : closing ? 'closing' : opening ? 'opening' : 'other';
              var fromTo = lastType + '->' + type;
              lastType = type;
              var padding = '';

              indent += transitions[fromTo];
              for (var j = 0; j < indent; j++) { padding += '  '; }
              if (fromTo == 'opening->closing') {
                  formatted = formatted.substr(0, formatted.length - 1) + ln + '\n'; // substr removes line break (\n) from prev loop
              } else {
                  formatted += padding + ln + '\n';
              }
          }

          return formatted;
      }

      function preview_CAP_XML() {
          // only one preview window allowed
          if (previewWindow) { previewWindow.destroy(); }

          var preview_xml_vals = generatedXML; //generate_CAP_XML();
          var display_xml = preview_xml_vals[0];

          WriteLog("info", "preview_CAP_XML called");

          try {
              // XTemplate from templates.js
              var display_html = CAP_Display_Template_Mini.apply(preview_xml_vals[1]);
          } catch (e) {
              display_html += '<div style="font-weight: bold; color: red">Template Error</div>';
          }
          display_xml = display_xml.replace(/</g, '&lt;');
          display_xml = display_xml.replace(/>/g, '&gt;');
          display_html += '<br><br><hr><br><br>';
          display_html += '<h1>CAP XML</h1><pre>' + display_xml + '</pre>';

          previewWindow = new Ext.Window({
              title: 'CAP Preview',
              closable: true,
              width: 700,
              height: 500,
              autoScroll: true,
              bodyStyle: 'background-color: white;',
              layout: 'fit',
              html: display_html
          });
          previewWindow.show(this);
      }

      function post_CAP_alert() {
          var posting_html = '<h1>Posting Alert</h1><img src="post/img/posting-wait.gif" alt="Posting Alert">';
          document.getElementById('postingBox').innerHTML = posting_html;
          postingTimeOut = setTimeout(post_timeout_error, 30000);
          // once a post is made, don't allow going back to retry with this session's data
          //TODO: not working
          //Ext.getCmp('card-prev').setDisabled();
          var new_cap_xml_vals = generatedXML;

          var postUrl = '';
          if (Ext.get('cap-version').getValue() == labelForCAP1_1) {
              postUrl = IPAWS_FORWARDER_URL_CAP1_1;
          }
          else if (Ext.get('cap-version').getValue() == labelForCAP1_2) {

              var cmas_enabled = Ext.getCmp('cap-cmamtext-checkbox').checked;
              var eas_enabled = Ext.getCmp('cap-eas-checkbox').checked;


              if (cmas_enabled && eas_enabled) {
                  postUrl = IPAWS_FORWARDER_URL_CAP1_2_EAS_CMAS;
              }
              else if (!cmas_enabled && eas_enabled) {
                  postUrl = IPAWS_FORWARDER_URL_CAP1_2_EAS;
              }
              else if (cmas_enabled && !eas_enabled) {
                  postUrl = IPAWS_FORWARDER_URL_CAP1_2_CMAS;
              }
              else {
                  postUrl = IPAWS_FORWARDER_URL_CAP1_2;
              }
          }


          var do_post = new OpenLayers.Request.POST({

              url: postUrl,
              //proxy: AJAX_PROXY_URL,
              //headers: {'Content-Type': 'application/common-alerting-protocol+xml'},
              headers: { 'Content-Type': 'application/xml' },
              data: new_cap_xml_vals[0],
              callback: post_CAP_result
          });

          WriteLog('Info', 'post_CAP_alert: url=' + postUrl + ' Data=' + new_cap_xml_vals[0]);
      }

      function post_timeout_error() {
          //TODO: cancel the do_post request handler
          var result_html = '<h1 style="color: red;">Failed Post</h1>' +
        '<div style="margin: 25px;">Posting Timed Out</div>' +
		'<a href="javascript:preview_CAP_XML();" style="color: grey;">View submitted XML</a>' +
        '<a href="javascript:preview_results();" style="color: grey;">View server response details</a>' +
        '<a href="' + MAIN_MENU_URL + '" style="color: blue;">Start Over</a>';
          document.getElementById('postingBox').innerHTML = result_html;

          WriteLog('Error', 'post_timeout_error: result=' + result_html);
      }

      function post_CAP_result(xhr) {
          var result_html = '';
          clearTimeout(postingTimeOut);
          postingResultText = xhr.responseText;
          var summary = CAP_Display_Template_Mini.apply(generatedXML[1]);
          if (xhr.status == '200' || xhr.status == '201') {
              result_html = '<h1 style="color: green;">Successful Post</h1>' + summary +
              //CAP_Display_Template_Mini.apply(generatedXML[1])+
			'<a href="javascript:preview_CAP_XML();" style="color: grey;">View submitted XML</a>' +
            '<a href="javascript:preview_results();" style="color: grey;">View server response details</a>' +
            '<a href="' + MAIN_MENU_URL + '" style="color: blue;">Start Over</a>';
          } else {
              postingResultText = postingResultText.replace(/</g, '&lt;');
              postingResultText = postingResultText.replace(/>/g, '&gt;');
              result_html = '<h1 style="color: red;">Failed Post</h1>' +
			'<a href="javascript:preview_CAP_XML();" style="color: grey;">View submitted XML</a>' +
			'<a href="javascript:preview_results();" style="color: grey;">View server response details</a>' +
            '<div style="margin: 25px;"><pre>' + postingResultText + '</pre></div>' +
            '<a href="' + MAIN_MENU_URL + '" style="color: blue;">Start Over</a>';
          }
          document.getElementById('postingBox').innerHTML = result_html;

          WriteLog('Info', 'post_CAP_result: result=' + result_html);
      }

      function parseXml(xml) {
          var dom = null;
          if (window.DOMParser) {
              try {
                  dom = (new DOMParser()).parseFromString(xml, 'text/xml');
              } catch (e) { dom = null; }
          } else if (window.ActiveXObject) {
              try {
                  dom = new ActiveXObject('Microsoft.XMLDOM');
                  dom.async = false;
                  if (!dom.loadXML(xml)) { dom = null; }
              } catch (e) { dom = null; }
          }
          if (dom == null) { alert('Unable to parse XML'); }
          return dom;
      }

      function preview_results() {
          // only one preview window allowed
          if (previewWindow) { previewWindow.destroy(); }

          var display_xml = postingResultText;
          var display_html = '';
          try {
              var atom_json = xmlJsonClass.xml2json(parseXml(postingResultText), '  ');
              var newAtom = JSON.parse(atom_json);
              // XTemplate from templates.js
              display_html += CAP_Display_Success.apply(newAtom);
              //display_html += Entry_Display_Template.apply(newAtom);
          } catch (e) {
              display_html += '<div style="font-weight: bold; color: red">Template Error</div>';
          }
          display_xml = display_xml.replace(/</g, '&lt;');
          display_xml = display_xml.replace(/>/g, '&gt;');
          display_html += '<br><br><hr><br><br>';
          display_html += '<h1>Server response XML</h1><pre>' + display_xml + '</pre>';

          previewWindow = new Ext.Window({
              title: 'Server Response',
              closable: true,
              width: 700,
              height: 500,
              autoScroll: true,
              bodyStyle: 'background-color: white;',
              layout: 'fit',
              html: display_html
          });
          previewWindow.show(this);
      }


      function download_xml() {

      }

      function WriteLog(level, msg) {

          if (capformSessionID == '') {
              var dateTimeNow = new Date();
              capformSessionID = "IPAWS-CAP-Generator-" + dateTimeNow.getUTCFullYear() + "-" + (dateTimeNow.getUTCMonth() + 1) + "-" + dateTimeNow.getUTCDate() + "-" +
               dateTimeNow.getUTCHours() + "-" + dateTimeNow.getUTCMinutes() + dateTimeNow.getUTCSeconds() + "-" + dateTimeNow.getUTCMilliseconds();
          }

          var do_post = new OpenLayers.Request.POST({
              url: "http://localhost:8000/CapLoggerService/WriteLog?sessionID=" + capformSessionID + "&level=" + level,
              data: msg,
              headers: { 'Content-Type': 'text/plain' }
          });
      }

  </script>
</head>
<body>
<div id="north" class="x-hide-display">
  <p>IPAWS CAP Generation Tool - if you can see this, your web browser
does not support this tool.  Please contact rgustafson@mitre.org</p>
</div>
</body>
</html>